package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	file, m, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}
	fmt.Println(file, m, err)

	//图片大小
	if m.Size > 3*1024*1024 {
		return &types.Response{
			Code: 500,
			Msg:  "图片大小不得超过3MB",
			Data: nil,
		}, nil
	}

	//图片格式
	ext := map[string]bool{
		".png":  true,
		".jpeg": true,
		".jpg":  true,
	}
	suffix := strings.ToLower(filepath.Ext(m.Filename))
	if ext[suffix] == false {
		return &types.Response{
			Code: 500,
			Msg:  "仅允许png、jpg、jpeg格式的图片",
			Data: nil,
		}, nil
	}

	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}

	return &types.Response{
		Code: 200,
		Msg:  "图片上传成功",
		Data: upload,
	}, nil
}
